package class03;

/**
 * <a href="https://leetcode.cn/problems/shan-chu-lian-biao-de-jie-dian-lcof/">剑指 Offer 18. 删除链表的节点</a>
 */
public class Code02_DeleteGivenValue {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int val) {
            this.val = val;
            this.next = null;
        }
    }

    public static ListNode removeValue(ListNode head, int val) {
        // head 来到第一个不需要删除的位置
        while (head != null) {
            if (head.val != val) {
                break;
            }
            head = head.next;
        }
        // 分别考虑下面两种情况
        // 1) head == null  // 结束循环
        // 2) head != null  // 判断是否等于number，if等于则跳过，如果不等于记录当下当前指针
        ListNode prev = head;
        ListNode cur = head;
        while (cur != null) {
            if (cur.val == val) {
                prev.next = cur.next;
            } else {
                prev = cur;
            }
            cur = cur.next;
        }
        return head;
    }
}
